<?php
/**
 * Implementation functions for working with filesystem
 * 
 * @package WFilesystem
 *
 */
require_once 'WFilesystem/errors.php';
class WFs {
	protected static $ROOT = '.';
	
	/**
	 * Returns file content as a string
	 * @param string $file path to file relative to root directory
	 * @return string
	 * @throws WK_Error
	 */
	public static function getContent ($file) {
		return file_get_contents(self::tryf($file, 'r'), true);		
	}
	
	/**
	 * Put string into the file 
	 * @param string $file  path to file relative to root directory
	 * @param string $content content
	 * @throws WK_Error
	 */
	public static function write ($file, $content) {
		file_put_contents(self::tryf($file, 'w'), $content);
		return true;
	}
	
	/**
	 * Copies file to destination
	 * @param string $src path to source file relative to root directory
	 * @param string $dest path to destination file relative to root directory
	 * @throws WK_Error
	 */
	public static function copy ($src, $dest) {
		self::write($dest, self::getContent($src));		
		return true;
	}
	
	/**
	 * Moves file to destination
	 * @param string $src path to source file relative to root directory
	 * @param string $dest path to destination file relative to root directory
	 * @throws WK_Error
	 */
	public static function move ($src, $dest) {
		self::copy($src, $dest);
		self::delete($src);
		return true;
	}
	
	/**
	 * Deletes file 
	 * @param string $file  path to file relative to root directory	 
	 * @throws WK_Error
	 */
	public static function delete ($file) {
		unlink(self::tryf($file));
		return true;
	}
	
	/**
	 * Sets root directory "Filesystem" component working in
	 * @param string $root
	 */
	public static function setRoot($root){
		self::$ROOT = $root;
	}
	
	/**
	 * Implementation of file existing and writable verifications
	 * @param string $file  path to file relative to root directory	 
	 * @param string $mode mode of working with file: "r" - read, "w" - write, "rw" - read and write
	 * @throws WK_Error
	 */
	private static function tryf ($file, $mode = 'rw') {
		$file = self::fp($file);
		if(($mode == 'r' || $mode == 'rw') && (!file_exists($file) || !is_file($file)))
			throw new WK_Error('File ' . $file . ' does not exists!', WERR_FILE_NOT_FOUND);
		if(($mode == 'r' || $mode == 'rw') && !is_readable($file)) 
			throw new WK_Error('File ' . $file . ' is not readable!', WERR_FILE_NOT_READABLE);
		if(($mode == 'w' || $mode == 'rw') && !is_writable($file) && !is_writable(dirname($file))) 
			throw new WK_Error('File ' . $file . ' is not writable!', WERR_FILE_NOT_WRITABLE);
		return $file;
	}
	
	private static function fp ($file) {
		return self::$ROOT . $file;
	}
}